package com.ctgu.demo.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo.dao.UserMapper;
import com.ctgu.demo.entity.User;
import com.ctgu.demo.error.EmBusinessError;
import com.ctgu.demo.error.exception.BusinessException;
import com.ctgu.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<User> getAll(int page, int size) {
        QueryWrapper<User> wrapper =new QueryWrapper<User>();
        IPage<User> userIPage = userMapper.selectPage(new Page<>(page,size), wrapper);
        return userIPage;
    }
    @Override
    public IPage<User> selectUser(String name, int page, int size){
        QueryWrapper<User> userIPage = new QueryWrapper<>();
        userIPage.like("id", name).or().like("user_nickname", name).or().like("user_telephone", name);
        IPage<User> usersMapper = userMapper.selectPage(new Page<>(page, size), userIPage);
        return usersMapper;
    }
    @Override
    public void register(User user) throws BusinessException {
        if (user == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        if (StringUtils.isEmpty(user.getUserNickname()) || StringUtils.isEmpty(user.getUserTelephone())) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        userMapper.insert(user);
    }
    @Override
    public User validateLogin(String telephone, String encryptPassword) throws BusinessException {

        //通过手机号获取用户信息
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("user_telephone", telephone);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        //比对用户加密码
        if (!StringUtils.equals(encryptPassword, user.getUserPassword())) {
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        return user;
    }

}
